當前位置: 首頁> 函數類別大全> is_a

is_a

檢查對像是否屬於此類,或者將此類作為其父類之一: 如果對象屬於該類或該類是此對象的父類則返回true
名稱:is_a
分類:類和對象
所屬語言:php
一句話介紹:檢查一個對像是否屬於指定的類或其子類

函數名:is_a()

適用版本:PHP 4, PHP 5, PHP 7

用法:is_a() 函數用於檢查一個對像是否屬於指定的類或其子類。

語法:bool is_a( object $object, string $class_name )

參數:

  • $object:要檢查的對象。
  • $class_name:要檢查的類名。

返回值:

  • 如果$object 是$class_name 的一個對像或者$class_name 的一個子類的對象,則返回true。
  • 如果$object 不是$class_name 的一個對像或者$class_name 的一個子類的對象,則返回false。

示例:

 class Person { public $name; } class Student extends Person { public $grade; } $person = new Person(); $student = new Student(); // 检查$person 是否是Person 类的对象if (is_a($person, 'Person')) { echo '$person 是Person 类的对象'; } else { echo '$person 不是Person 类的对象'; } // 检查$student 是否是Person 类的对象if (is_a($student, 'Person')) { echo '$student 是Person 类的对象'; } else { echo '$student 不是Person 类的对象'; } // 检查$student 是否是Student 类的对象if (is_a($student, 'Student')) { echo '$student 是Student 类的对象'; } else { echo '$student 不是Student 类的对象'; }

輸出:

 $person 是Person 类的对象$student 是Person 类的对象$student 是Student 类的对象

以上示例中,我們定義了一個Person 類和一個Student 類,Student 類是Person 類的子類。我們創建了一個$person 對象和一個$student 對象。使用is_a() 函數來檢查這些對象的類屬關係。第一個檢查表明$person 是Person 類的對象,第二個檢查表明$student 也是Person 類的對象,第三個檢查表明$student 是Student 類的對象。

同類函數